package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.activity.domain.ActBusinessFlowRel;
import com.ruoyi.activity.service.IActBusinessFlowRelService;
import com.ruoyi.activity.service.IFlowService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.enums.BusinessFlag;
import com.ruoyi.system.domain.CompanyInfo;
import com.ruoyi.system.domain.WcPatentApplication;
import com.ruoyi.system.domain.WcPatentApplicationAncillary;
import com.ruoyi.system.domain.WcPatentApplicationCompany;
import com.ruoyi.system.domain.vo.business.*;
import com.ruoyi.system.domain.vo.coopHan.CulvertApprovalCompanyVo;
import com.ruoyi.system.dto.coopHan.PageCulvertNoticeDto;
import com.ruoyi.system.dto.handleRecord.IdSearchVO;
import com.ruoyi.system.mapper.CompanyInfoMapper;
import com.ruoyi.system.mapper.WcPatentApplicationMapper;
import com.ruoyi.system.service.IWcPatentApplicationAncillaryService;
import com.ruoyi.system.service.IWcPatentApplicationCompanyService;
import com.ruoyi.system.service.IWcPatentApplicationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.List;

/**
 * 剧本备案申请Service业务层处理
 *
 * @author ruoyi
 * @date 2024-02-28
 */
@Service
public class WcPatentApplicationServiceImpl extends ServiceImpl<WcPatentApplicationMapper, WcPatentApplication> implements IWcPatentApplicationService {
    @Autowired
    private WcPatentApplicationMapper wcPatentApplicationMapper;

    @Autowired
    private IWcPatentApplicationAncillaryService ancillaryService;

    @Autowired
    private IWcPatentApplicationCompanyService wcPatentApplicationCompanyService;

    @Autowired
    private IActBusinessFlowRelService actBusinessFlowRelService;

    @Autowired
    private IFlowService flowServiceImpl;

    private final static String SL = "受理";
    private final static String ZJPS = "专家评审";
    private final static String SCJD = "审查决定";
    private final static String GSFZ = "公示发证";


    /**
     * 查询剧本备案申请
     *
     * @param id 剧本备案申请主键
     * @return 剧本备案申请
     */
    @Override
    public WcPatentApplication selectWcPatentApplicationById(Long id) {
        return wcPatentApplicationMapper.selectWcPatentApplicationById(id);
    }

    /**
     * 查询剧本备案申请列表
     *
     * @param wcPatentApplication 剧本备案申请
     * @return 剧本备案申请
     */
    @Override
    public List<WcPatentApplication> selectWcPatentApplicationList(WcPatentApplication wcPatentApplication) {
        return wcPatentApplicationMapper.selectWcPatentApplicationList(wcPatentApplication);
    }

    /**
     * 新增剧本备案申请
     *
     * @param wcPatentApplication 剧本备案申请
     * @return 结果
     */
    @Override
    public int insertWcPatentApplication(WcPatentApplication wcPatentApplication) {
        wcPatentApplication.setCreateTime(DateUtils.getNowLocalDateTime());
        return wcPatentApplicationMapper.insert(wcPatentApplication);
    }

    /**
     * 修改剧本备案申请
     *
     * @param wcPatentApplication 剧本备案申请
     * @return 结果
     */
    @Override
    public int updateWcPatentApplication(WcPatentApplication wcPatentApplication) {
        wcPatentApplication.setUpdateTime(DateUtils.getNowLocalDateTime());
        return wcPatentApplicationMapper.updateWcPatentApplication(wcPatentApplication);
    }

    /**
     * 批量删除剧本备案申请
     *
     * @param ids 需要删除的剧本备案申请主键
     * @return 结果
     */
    @Override
    public int deleteWcPatentApplicationByIds(String ids) {
        return wcPatentApplicationMapper.deleteWcPatentApplicationByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除剧本备案申请信息
     *
     * @param id 剧本备案申请主键
     * @return 结果
     */
    @Override
    public int deleteWcPatentApplicationById(Long id) {
        return wcPatentApplicationMapper.deleteWcPatentApplicationById(id);
    }

    @Override
    public Page<WcPatentApplicationSelectListVO> list(WcPatentApplicationSelectListDto dto) {
        Long userId = SecurityUtils.getUserId();
        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getList(page, dto);
        return page;
    }
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Override
    public WcPatentApplicationDetailVO selectWcPatentApplicationDetailVOById(Long id) {
        WcPatentApplication application = getById(id);
        WcPatentApplicationDetailVO result = new WcPatentApplicationDetailVO();
        BeanUtils.copyBeanProp(result, application);
        WcPatentApplicationAncillary applicationAncillary = ancillaryService
                .getOne(new LambdaQueryWrapper<WcPatentApplicationAncillary>()
                        .eq(WcPatentApplicationAncillary::getWcPatentApplicationId, application.getId()));
        BeanUtils.copyBeanProp(result, applicationAncillary);
        List<WcPatentApplicationCompany> list = wcPatentApplicationCompanyService
                .list(new LambdaQueryWrapper<WcPatentApplicationCompany>()
                        .eq(WcPatentApplicationCompany::getWcPatentApplicationId, application.getId()));
        result.setUnit(list);
        ActBusinessFlowRel actBusinessFlowRel = actBusinessFlowRelService
                .getOne(new LambdaQueryWrapper<ActBusinessFlowRel>()
                        .eq(ActBusinessFlowRel::getBusinessType, BusinessFlag.WC_PATENT.getValue())
                        .eq(ActBusinessFlowRel::getBusinessId, application.getId()));
        if(actBusinessFlowRel != null){
            BeanUtils.copyBeanProp(result, actBusinessFlowRel);
            // 插入审批状态
            result.setFlowState(actBusinessFlowRel.getFlowState());
        }

        if(StringUtils.isNotBlank(application.getProductionUnit())){
            CompanyInfo companyInfo= companyInfoMapper.selectCompanyInfoByCompanyName(application.getProductionUnit());
            if(companyInfo!=null){
                CulvertApprovalCompanyVo culvertApprovalCompanyVo=new CulvertApprovalCompanyVo();
                culvertApprovalCompanyVo.setCompanyId(companyInfo.getCompanyId().toString());
                culvertApprovalCompanyVo.setCompanyName(companyInfo.getCompanyName());
                culvertApprovalCompanyVo.setBusinessLicense(companyInfo.getBusinessLicensePath());
                culvertApprovalCompanyVo.setLegalPersonName(companyInfo.getLegalRepresentative());
                culvertApprovalCompanyVo.setLegalPersonPhone(companyInfo.getLegalRepresentativePhone());
                result.setCompanyVo(culvertApprovalCompanyVo);
            }
        }

        return result;
//        return wcPatentApplicationMapper.selectWcPatentApplicationDetailVOById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSave(WcPatentApplicationSaveVO saveVO) throws Exception {
        WcPatentApplication entity = new WcPatentApplication();
        entity.setMovieName(saveVO.getMovieName());
        entity.setNumber(saveVO.getNumber());
        entity.setRemark(saveVO.getRemark());
        entity.setIsOutbox(saveVO.getIsOutbox());
        entity.setProductionUnit(saveVO.getProductionUnit());
        save(entity);


        WcPatentApplicationAncillary ancillary = new WcPatentApplicationAncillary();
        ancillary.setWcPatentApplicationId(entity.getId());
        ancillary.setAncillary1Name(saveVO.getAncillary1Name());
        ancillary.setAncillary1Url(saveVO.getAncillary1Url());

        ancillary.setAncillary2Name(saveVO.getAncillary2Name());
        ancillary.setAncillary2Url(saveVO.getAncillary2Url());

        ancillary.setAncillary3Name(saveVO.getAncillary3Name());
        ancillary.setAncillary3Url(saveVO.getAncillary3Url());

        ancillary.setAncillary4Name(saveVO.getAncillary4Name());
        ancillary.setAncillary4Url(saveVO.getAncillary4Url());

        ancillary.setAncillary5Name(saveVO.getAncillary5Name());
        ancillary.setAncillary5Url(saveVO.getAncillary5Url());

        ancillary.setAncillary6Name(saveVO.getAncillary6Name());
        ancillary.setAncillary6Url(saveVO.getAncillary6Url());

        ancillaryService.save(ancillary);

        List<WcPatentApplicationCompanyVo> unit = saveVO.getUnit();
        List<WcPatentApplicationCompany> companys = new ArrayList<>();
        if (!CollectionUtils.isEmpty(unit)) {
            for (WcPatentApplicationCompanyVo company : unit) {
                WcPatentApplicationCompany wcPatentApplicationCompany = new WcPatentApplicationCompany();
                wcPatentApplicationCompany.setCompanyName(company.getCompanyName());
                wcPatentApplicationCompany.setBusinessLicense(company.getBusinessLicense());
                wcPatentApplicationCompany.setLegalPersonIdCardFront(company.getLegalPersonIdCardFront());
                wcPatentApplicationCompany.setLegalPersonIdCardSide(company.getLegalPersonIdCardSide());
                wcPatentApplicationCompany.setWcPatentApplicationId(entity.getId());
                companys.add(wcPatentApplicationCompany);
            }

        }
//        ancillary.setProductionUnit(saveVO.getProductionUnit());
        wcPatentApplicationCompanyService.saveBatch(companys);
        String processInstanceId = "";
        if(saveVO.getIsOutbox().equals("0")){
            processInstanceId = flowServiceImpl.start(entity.getId(), BusinessFlag.WC_PATENT.getValue());
        }

        return processInstanceId;
    }

    @Override
    public String updateSave(WcPatentApplicationUpdateVO saveVO) throws Exception {
        WcPatentApplication entity = new WcPatentApplication();
        entity.setMovieName(saveVO.getMovieName());
        entity.setNumber(saveVO.getNumber());
        entity.setRemark(saveVO.getRemark());
        entity.setProductionUnit(saveVO.getProductionUnit());
        updateById(entity);


        WcPatentApplicationAncillary ancillary = new WcPatentApplicationAncillary();
        ancillary.setWcPatentApplicationId(entity.getId());
        ancillary.setAncillary1Name(saveVO.getAncillary1Name());
        ancillary.setAncillary1Url(saveVO.getAncillary1Url());

        ancillary.setAncillary2Name(saveVO.getAncillary2Name());
        ancillary.setAncillary2Url(saveVO.getAncillary2Url());

        ancillary.setAncillary3Name(saveVO.getAncillary3Name());
        ancillary.setAncillary3Url(saveVO.getAncillary3Url());

        ancillary.setAncillary4Name(saveVO.getAncillary4Name());
        ancillary.setAncillary4Url(saveVO.getAncillary4Url());

        ancillary.setAncillary5Name(saveVO.getAncillary5Name());
        ancillary.setAncillary5Url(saveVO.getAncillary5Url());

        ancillary.setAncillary6Name(saveVO.getAncillary6Name());
        ancillary.setAncillary6Url(saveVO.getAncillary6Url());
        ancillaryService.updateById(ancillary);

        List<WcPatentApplicationCompanyVo> unit = saveVO.getUnit();
        List<WcPatentApplicationCompany> companys = new ArrayList<>();
        if (!CollectionUtils.isEmpty(unit)) {
            for (WcPatentApplicationCompanyVo company : unit) {
                WcPatentApplicationCompany wcPatentApplicationCompany = new WcPatentApplicationCompany();
                wcPatentApplicationCompany.setCompanyName(company.getCompanyName());
                wcPatentApplicationCompany.setBusinessLicense(company.getBusinessLicense());
                wcPatentApplicationCompany.setLegalPersonIdCardFront(company.getLegalPersonIdCardFront());
                wcPatentApplicationCompany.setLegalPersonIdCardSide(company.getLegalPersonIdCardSide());
                wcPatentApplicationCompany.setWcPatentApplicationId(entity.getId());
                companys.add(wcPatentApplicationCompany);
            }
        }
        wcPatentApplicationCompanyService.updateBatchById(companys);

        String processInstanceId = "";
        if(saveVO.getIsOutbox().equals("0")){
            processInstanceId = flowServiceImpl.start(entity.getId(), BusinessFlag.WC_PATENT.getValue());
        }

        return processInstanceId;

    }

    @Override
    public Page<WcPatentApplicationSelectListVO> pageNotice(PageCulvertNoticeDto dto) {
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        // Page<WcPatentApplicationSelectListVO> pageNotice = wcPatentApplicationMapper.getPageNotice(page, dto);
        return page;
    }

    /**
     * 电影剧本备案--查询剧本备案受理列表
     * @param dto
     * @return
     */
    @Override
    public Page<WcPatentApplicationSelectListVO> acceptanceList(WcPatentApplicationSelectListDto dto) {
        Long userId = SecurityUtils.getUserId();
        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getAcceptanceList(page, dto, SL);
        return page;
    }

    /**
     * 电影剧本备案--查询剧本备案专家评审列表
     * @param dto
     * @return
     */
    @Override
    public Page<WcPatentApplicationSelectListVO> expertReviewList(WcPatentApplicationSelectListDto dto) {
        Long userId = SecurityUtils.getUserId();
        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getAcceptanceList(page, dto, ZJPS);
        return page;
    }

    /**
     * 电影剧本备案--查询剧本备案审查决定列表
     * @param dto
     * @return
     */
    @Override
    public Page<WcPatentApplicationSelectListVO> reviewDecisionList(WcPatentApplicationSelectListDto dto) {
        Long userId = SecurityUtils.getUserId();
        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getAcceptanceList(page, dto, SCJD);
        return page;
    }

    /**
     * 电影剧本备案--查询剧本备案公示发证列表
     * @param dto
     * @return
     */
    @Override
    public Page<WcPatentApplicationSelectListVO> publicizeCertificationList(WcPatentApplicationSelectListDto dto) {
        Long userId = SecurityUtils.getUserId();
        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationSelectListVO> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getAcceptanceList(page, dto, GSFZ);
        return page;
    }

    /**
     *  电影剧本备案--查询剧本备案公示信息列表
     * @param dto
     * @return
     */
    @Override
    public Page<WcPatentApplicationPublicityInfoListVo> publicityInfoList(WcPatentApplicationPublicityInfoListDto dto) {
        // todo 用户信息
//        Long userId = SecurityUtils.getUserId();
//        dto.setApprovalUserId(userId);
        Page<WcPatentApplicationPublicityInfoListVo> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPageNum());
        wcPatentApplicationMapper.getPublicityInfoList(page, dto);
        return page;
    }

    @Override
    public String addRecommendation(WcPatentApplicationRecommendationVO saveVO) {
        saveVO.setRecommendationTime(DateUtils.getNowLocalDateTime());
        wcPatentApplicationMapper.saveRecommendation(saveVO);
        return "";
    }

    @Override
    public List<WcPatentApplicationRecommendationVO> getRecommendationList(IdSearchVO saveVO) {
        if(StringUtils.isBlank(saveVO.getId())){
            return  new ArrayList<>();
        }
        return  wcPatentApplicationMapper.getRecommendationList(saveVO.getId());
    }


}
